package com.cvai.controller;


import com.cvai.R.Result;
import com.cvai.domain.po.File;
import com.cvai.service.IFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cv
 * @since 2025-03-09
 */
@RestController
@RequestMapping("/upload")
@Slf4j
@RequiredArgsConstructor
public class FileController {
    private final String UPLOAD_DIR = "E:\\Temp\\cvai";
    private final IFileService fileService;
    private final String[] ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "txt"};
    private final String[] PICTURE_EXTENSIONS = {"jpg", "jpeg", "png"};

    @PostMapping
    public ResponseEntity upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty())
            return ResponseEntity.badRequest().body("文件为空");
        Map<String, Object> result = new HashMap<>();
        result.put("originalName", file.getOriginalFilename());

        String originalFilename = file.getOriginalFilename();
        log.info("上传", originalFilename);
        String[] arr = originalFilename.split("\\.");
        String s = arr[arr.length - 1];
        if (!Arrays.stream(ALLOWED_EXTENSIONS).anyMatch(s::equals)) {
            return ResponseEntity.badRequest().body("文件格式不正确");
        }

        try {
            // 生成存储文件名
            String newFileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_DIR).resolve(newFileName);
            Files.copy(file.getInputStream(), filePath);
            File myFile = new File();
            if (Arrays.stream(PICTURE_EXTENSIONS).anyMatch(s::equals)) {
                myFile.setIsPicture(1);
            }
            // 保存到数据库

            myFile.setFilePath(filePath.toString());

            fileService.save(myFile);

            result.put("status", "success");
            result.put("fileId", myFile.getId()); // 返回数据库生成的ID
            result.put("savedName", newFileName);

        } catch (Exception e) {
            result.put("status", "failed");
            result.put("error", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

        log.info("上传成功"+originalFilename);
        return ResponseEntity.ok(Map.of(
                "message", "批量上传完成",
                "details", result
        ));
    }
}
